<style type="text/css">
    .layui-card-body {
        background-color: #fff;
        padding: 10px;
        margin-top: 10px;
        border: 1px solid #e6e6e6;
    }

    .layui-tab-card > .layui-tab-title {
        background-color: #f9f9f9;
        border-bottom: none;
    }

    .layui-tab-content {
        padding: 0;
    }

    .layui-table, .layui-table-view {
        margin: 0;
    }

    .layui-margin-10 {
        margin: 10px;
    }
</style>
<script src="__STATIC_JS__jquery.form.js" type="text/javascript" charset="utf-8"></script>

<form class="layui-form seller-form" action="">
    <div class="layui-form-item">

        <div class="layui-inline">
            <label class="layui-form-label">素材名称：</label>
            <div class="layui-input-inline seller-inline-4">
                <input type="text" name="name" lay-verify="title" placeholder="请输入素材名称" autocomplete="off"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">上架状态：</label>
            <div class="layui-input-inline seller-inline-2">
                <select name="marketable" id="marketable">
                    <option value="">全部</option>
                    <option value="1">上架</option>
                    <option value="2">下架</option>
                </select>
            </div>
        </div>

        <div class="layui-inline">
            <button class="layui-btn layui-btn-sm" lay-submit lay-filter="goods-search"><i
                    class="iconfont icon-chaxun"></i>筛选
            </button>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-inline">
            <button class="layui-btn layui-btn-sm" id="addUserPic" lay-filter="goods-add"><i
                    class="layui-icon">&#xe608;</i>添加素材
            </button>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">批量操作：</label>
            <div class="layui-input-inline seller-inline-2">
                <select name="batchOperate" id="batchOperate" lay-filter="batchOperate">
                    <option value=""></option>
                    <option value="marketable_up">上架</option>
                    <option value="marketable_down">下架</option>
                    <option value="label">打标签</option>
                    <option value="dellabel">去标签</option>
                    <option value="del">删除</option>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <button type="button" class="layui-btn layui-btn-sm" lay-submit lay-filter="import-goods"><i
                    class="layui-icon"></i>导入素材
            </button>
        </div>
        <div class="layui-inline">
            <button class="layui-btn layui-btn-sm" lay-submit lay-filter="export-goods"><i
                    class="iconfont icon-msnui-cloud-download" style="font-size: 20px !important;"></i>导出
            </button>
        </div>
        <div class="layui-inline">
            <button class="layui-btn layui-btn-sm" id="Goods" lay-submit lay-filter="advance-goods-search"><i
                    class="iconfont icon-shaixuan"></i>高级筛选
            </button>
        </div>
    </div>
</form>

<div class="layui-card-body">
    <div class="layui-tab layui-tab-card" lay-filter="goods-tab">
        <ul class="layui-tab-title">
            <li class="layui-this" lay-id="all">全部素材<span class="layui-badge layui-bg-gray">{$statics.totalGoods|default=0}</span>
            </li>
            <li lay-id="up">上架素材<span class="layui-badge layui-bg-green">{$statics.totalMarketableUp|default=0}</span>
            </li>
            <li lay-id="down">下架素材<span
                    class="layui-badge layui-bg-black">{$statics.totalMarketableDown|default=0}</span></li>
        </ul>
        <div class="layui-tab-content">
            <table id="UserPicTable" lay-filter="test"></table>
        </div>
    </div>
</div>


<div id="exportGoods" style="display: none;">
    <form class="layui-form export-form" action="">
        <div class="layui-form-item">
            <div class="layui-margin-10">
                <blockquote class="layui-elem-quote layui-text">
                    请先选中或筛选要导出的素材
                </blockquote>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label">任务名称：</label>
                <input type="text" name="taskname" lay-verify="title" style="width:200px;" placeholder="请输入任务名称"
                       autocomplete="off" class="layui-input">
            </div>
        </div>
    </form>
</div>

<div id="importGoods" style="display: none;">
    <form class="layui-form import-form" method="post" action="{:url('ietask/import')}" enctype="multipart/form-data">
        <div class="layui-form-item">
            <div class="layui-margin-10">
                <blockquote class="layui-elem-quote layui-text">
                    请先下载<a href="{:url('ietask/importTemplete',['tplName'=>'goods'])}">导入模板</a>
                </blockquote>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">
                    <input type="file" class="layui-file" name="importFile" id="importFile">
                    <input type="hidden" name="model" value="Goods">
                </label>
            </div>
        </div>
    </form>
</div>
<script>
    var table, window_box;
    layui.use(['form', 'layedit', 'upload', 'laydate', 'table', 'element'], function () {
        var upload = layui.upload;
        var element = layui.element;
        var filter = {};

        table = layui.table.render({
            elem: '#UserPicTable',
            height: 'full-330',
            cellMinWidth: '80',
            page: 'true',
            limit: '20',
            url: "{:url('UserPic/index')}?_ajax=1",
            id: 'UserPicTable',
            cols: [[
                {type: 'checkbox', fixed: 'left'},
                {type: 'numbers'},
                {field: 'user_id', width: 150, title: '所属用户', align: 'center'},
                {field:'image', width:100,title:'缩略图', align: 'center',templet: function(data){
                        return '<a href="javascript:void(0);" onclick=viewImage("'+data.image+'")><image style="max-width:30px;max-height:30px;" src="'+data.image+'"/></a>';
                    }},
                {field: 'sort', edit: 'text', width: 80, title: '排序', align: 'center'},

                {
                    field: 'marketable', width: 100, title: '上下架', align: 'center', templet: function (data) {
                        if (data.marketable == '1') {
                            return '<a href="javascript:void(0);">上架</a>';
                        } else {
                            return '<a href="javascript:void(0);">下架</a>';
                        }
                    }
                },
                {
                    field: 'operating', width: 250, title: '操作', align: 'center', templet: function (data) {
                        var html = '';
                        html += '<a class="layui-btn layui-btn-xs edit-class" data-id="' + data.id + '">编辑</a>';
                        html += '<a class="layui-btn layui-btn-danger layui-btn-xs del-class" data-name="' + data.name + '" data-id="' + data.id + '">删除</a>';
                        return html;
                    }, fixed: 'right'
                }
            ]]
        });

        layui.table.on('edit(test)', function (obj) {

            JsPost("{:url('UserPic/updateSort')}", {
                    'field': obj.field,
                    'value': obj.value,
                    'id': obj.data.id
                }, function (res) {
                    layer.msg(res.msg, {time: 1500}, function () {
                        if (res.status) {
                            table.reload();
                        }
                    });
                }
            );
        });

        //素材导入
        layui.form.on('submit(import-goods)', function (data) {
            layer.open({
                type: 1,
                title: '素材导入',
                area: ['400px', '290px'], //宽高
                btn: ['确定', '取消'],
                content: $("#importGoods").html(),
                yes: function (index, obj) {
                    $(obj).find('.import-form').ajaxSubmit({
                        type: 'post',
                        dataType: 'json',
                        success: function (result) {
                            layer.msg(result.msg, {time: 1500}, function () {
                                if (result.status) {
                                    table.reload();
                                    layer.closeAll();
                                }
                            });
                        },
                        error: function (result) {
                            layer.msg("导入失败");
                        }
                    });
                }, btn2: function () {
                    layer.closeAll();
                }
            });
        });

        //素材导出
        layui.form.on('submit(export-goods)', function (data) {
            layer.open({
                type: 1,
                title: '素材导出',
                area: ['400px', '290px'], //宽高
                btn: ['确定', '取消'],
                content: $("#exportGoods").html(),
                yes: function () {
                    //判断是否有选中
                    var checkStatus = layui.table.checkStatus('UserPicTable');
                    var checkData = checkStatus.data;
                    var length = checkStatus.data.length;
                    var selectIds = '';
                    var ids = [];
                    if (length) {
                        $.each(checkData, function (i, obj) {
                            ids.push(obj.id);
                        });
                    }
                    var filter = $(".seller-form").serialize();
                    filter += '&ids=' + ids;
                    $(".export-form:last").append("<input type='hidden' name='filter' value='" + filter + "'>");
                    var data = $(".export-form:last").serializeArray();

                    data.push({'name': 'model', 'value': 'Goods'});
                    JsPost("{:url('Ietask/export')}", data, function (res) {
                            layer.msg(res.msg, {time: 1500}, function () {
                                if (res.status) {
                                    table.reload();
                                    layer.closeAll();
                                }
                            });
                        }
                    );
                }, btn2: function () {
                    layer.closeAll();
                }
            });
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        element.on('tab(goods-tab)', function (data) {
            var type = this.getAttribute('lay-id');
            if (type == 'all') {
                filter = {};
            } else if (type == 'up') {
                delete filter.warn;
                filter['marketable'] = '1';
            } else if (type == 'down') {
                delete filter.warn;
                filter['marketable'] = '2';
            } else if (type == 'warn') {
                delete filter.marketable;
                filter['warn'] = 'true';
            }

            var basefilter = $(".seller-form").serializeArray();
            $.each(basefilter, function (i, obj) {
                if (!filter.hasOwnProperty(obj.name)) {
                    filter[obj.name] = obj.value;
                }
            });
            table.reload({
                where: filter
                , page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
        });

        layui.form.on('submit(goods-search)', function (data) {
            var tempfilter = $.extend({}, filter, data.field);//合并tab筛选和普通搜索
            table.reload({
                where: tempfilter
                , page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        layui.form.on('button("goods-add")', function (data) {
            return false;
        });

        layui.form.on('submit(advance-goods-search)', function (data) {
            JsGet("{:url('UserPic/goodsSearch')}", function (html) {
                layer.open({
                    type: 1,
                    area: ['500px', '450px'],
                    fixed: false,
                    title: '高级筛选',
                    maxmin: false,
                    shade: 0,
                    content: html,
                    btn: ['确定', '取消'],
                    yes: function (index, layero) {
                        var searchData = getFormData();
                        var advance = $(".advance-goods-search").serializeArray();
                        $.each(advance, function (i, obj) {
                            $(".seller-form").append('<input type="hidden" name="' + obj.name + '" value="' + obj.value + '">');
                        })

                        table.reload({
                            where: searchData
                            , page: {
                                curr: 1 //重新从第 1 页开始
                            }
                        });
                        layer.close(index);
                    }
                    , btn2: function () {
                        layer.closeAll();
                    }
                });
            });


            return false;
        });
        //批量操作
        layui.form.on('select(batchOperate)', function (data) {
            //判断是否有选中
            var checkStatus = layui.table.checkStatus('UserPicTable');
            var checkData = checkStatus.data;
            var operate = data.value;
            var length = checkStatus.data.length;
            if (length <= 0) {
                layer.msg("请先选要操作的数据");
                return false;
            }
            var ids = [];
            $.each(checkData, function (i, obj) {
                ids.push(obj.id);
            });
            switch (operate) {
                case 'marketable_up':
                    marketable(ids, 'up');
                    break;
                case 'marketable_down':
                    marketable(ids, 'down');
                    break;
                case 'label':
                    setLabel(ids);
                    break;
                case 'del':
                    delFont(ids);
                    break;
                case 'dellabel':
                    dellabel(ids);
                    break;
                default :
                    layer.msg('请选择操作类型');
                    return false;
            }
        });

        //上下架操作
        function marketable(data, type) {
            layer.confirm('是否确定该操作？', {
                    title: '提示',
                    btn: ['是', '否'] //按钮
                }, function () {
                    JsPost("{:url('UserPic/batchMarketable')}", {'ids': data, 'type': type}, function (res) {
                            layer.msg(res.msg);
                            table.reload();
                        }
                    );
                }
                , function () {
                    layer.closeAll();
                }
            );
        }

        //设置标签
        function setLabel(data) {
            JsPost('{:url("label/setLabel")}', {'ids': data, 'model': 'Goods'}, function (res) {
                layer.open({
                    type: 1,
                    area: ['700px', '450px'],
                    fixed: false, //不固定
                    title: '标签设置',
                    shade: 0,
                    content: res.data,
                    btn: ['确定', '取消'],
                    yes: function (index, layero) {
                        //do something
                        var selectedData = getSelected();
                        if (selectedData) {
                            JsPost("{:url('Label/doSetLabel')}", {
                                    'ids': data,
                                    'label': selectedData,
                                    'model': 'Goods'
                                }, function (res) {
                                    layer.msg(res.msg);
                                    table.reload();
                                    layer.close(index);
                                }
                            );
                        }

                    }
                    , btn2: function () {
                        layer.closeAll();
                    }
                });
            });
        }


        //删除素材
        function delFont(data) {
            layer.confirm('确认删除选中素材吗？', {
                title: '提示', btn: ['确认', '取消'] //按钮
            }, function () {
                JsPost("{:url('UserPic/batchDel')}", {'ids': data}, function (res) {
                        layer.msg(res.msg);
                        table.reload();
                    }
                );
            });
        }

        //监听 操作状态
        layui.form.on('switch(is_hot)', function (obj) {
            JsPost("{:url('UserPic/changeState')}", {
                id: this.value,
                type: 'hot',
                state: obj.elem.checked
            }, function (res) {
                layer.msg(res.msg);
            });
        });
        layui.form.on('switch(is_recommend)', function (obj) {
            JsPost("{:url('UserPic/changeState')}", {
                id: this.value,
                type: 'rec',
                state: obj.elem.checked
            }, function (res) {
                layer.msg(res.msg);
            });
        });
    });

    //编辑素材
    $(document).on('click', '.edit-class', function () {
        var id = $(this).attr('data-id');
        var url = '{:url("UserPic/edit")}';

        $.ajax({
            url: url,
            type: 'get',
            data: {
                id:id
            },
            success: function(e){
                window_box = layer.open({
                    type: 1,
                    title: '编辑素材',
                    area: ['600px', '780px'], //宽高
                    content: e
                });
            }
        });
        return false;


    });

    //删除素材
    $(document).on('click', '.del-class', function () {
        var id = $(this).attr('data-id');
        var goodsName = $(this).attr('data-name');
        layer.confirm('确认删除素材：' + goodsName + ' 吗？', {
            title: '提示', btn: ['确认', '取消'] //按钮
        }, function () {
            delClass(id);
        });
    });

    //删除操作
    function delClass(id) {
        $.ajax({
            url: '{:url("UserPic/delete")}',
            type: 'post',
            data: {
                'id': id
            },
            success: function (e) {
                layer.msg(e.msg, {time: 1300}, function () {
                    table.reload('UserPicTable');
                });
            }
        });
    }

    //添加素材
    $(document).on('click', '#addUserPic', function(){
        $.ajax({
            url: '{:url("UserPic/add")}',
            type: 'get',
            data: {

            },
            success: function(e){
                window_box = layer.open({
                    type: 1,
                    title: '添加素材',
                    area: ['600px', '780px'], //宽高
                    content: e
                });
            }
        });
        return false;
    });
    //添加保存数据
    $(document).on('click', '.add-save-btn', function(){
        var cate_id = $("#cate_id").val();
        var name = $("#name").val();
        var image_id = $("#image_value_image_id").val();
        var sort = $("#sort").val();
        var price = $("#price").val();
        var marketable = $("input[name='marketable']").val();
        var error = false;
        if(name.length > 6 || name.length < 1){
            error = true;
            layer.msg('分类名称在1-6个字符之间', {time: 1300});
            return false;
        }
        if(sort < 1 || sort > 100){
            error = true;
            layer.msg('请填写1-100的排序值，越小越靠前', {time: 1300});
            return false;
        }

        if(!error){
            $.ajax({
                url: '{:url("UserPic/add")}',
                type: 'post',
                data: {
                    'cate_id': cate_id,
                    'name': name,
                    'image_id': image_id,
                    'sort': sort,
                    'marketable':marketable,
                    'price':price,
                },
                dataType: 'json',
                success: function(e){
                    if(e.status === true){
                        layer.close(window_box);
                        layer.msg(e.msg, {time: 1300}, function(){
                            table.reload('categories');
                        });
                    }else{
                        layer.msg(e.msg, {time: 1300});
                    }
                }
            })
        }
    });

    //编辑保存数据
    $(document).on('click', '.edit-save-btn', function(){
        var id = $("#id").val();
        var cate_id = $("#cate_id").val();
        var name = $("#name").val();
        var image_id = $("#image_value_image_id").val();
        var sort = $("#sort").val();
        var price = $("#price").val();
        var marketable = $("input[name='marketable']").val();
        if(name.length > 6){
            layer.msg('分类名称不能大于6个字符');
            return false;
        }else{
            $.ajax({
                url: '{:url("UserPic/edit")}',
                type: 'post',
                dataType: 'json',
                data: {
                    'id': id,
                    'cate_id': cate_id,
                    'name': name,
                    'image_id': image_id,
                    'sort': sort,
                    'marketable':marketable,
                    'price':price
                },
                success: function(e){
                    if(e.status === true){
                        layer.close(window_box);
                        layer.msg(e.msg, {item: 1300}, function(){
                            table.reload('categories');
                        });
                    }else{
                        layer.msg(e.msg, {time: 1300});
                    }
                }
            });
        }
    });

</script>

<script type="text/html" id="hot">
    <input type="checkbox" name="is_hot" value="{{d.id}}" lay-skin="switch" lay-text="是|否" lay-filter="is_hot" {{
           d.is_hot== 1 ? 'checked' : '' }}>
</script>

<script type="text/html" id="rec">
    <input type="checkbox" name="is_recommend" value="{{d.id}}" lay-skin="switch" lay-text="是|否"
           lay-filter="is_recommend" {{ d.is_recommend== 1 ? 'checked' : '' }}>
</script>